let fetch = require("../../utils/fetch");
let mta = require('../../utils/mta_analysis.js');

let app = getApp();
Page({
	data: {

		urlAddress: getApp().globalData.imageUrl,
		shopMarket: {},
		imageUrl: getApp().globalData.imageUrl,
		timeType: [],
		leftStyle: '',
		pickerArr: [],
		showTimePick: false, //是否显示时间
		showFloat: false, //是否显示背景
		showPayPick: false, //是否显示支付渠道
		showOrdermsg: false, //是否显示订单详情
		payType: null, //支付方式
		payText: '',
		balance: 0,
		shopInfo: {},
		chooseTime: [],
		addressString: '请选择', //字体地址
		timeString: '请选择', //自提时间
		class1: 'menu_select',
		class2: 'menu_unselect',
		chooseAddress: '请选择地址', //配送地址
		peisongTime: '请选择', //配送时间
		getTimes: null, //自提时间
		chooseTimes: null, //选择配送时间
		chooseNote: null, //备注
		isShow: false, //密码输入框
		input_type: true, //免密自动聚焦
		balanceP: false, //是否显示密码框
		orderCode: '', //预订单号
		timeNote: '', //选择事件提示
		orderMsgaddress: '',
		orderMsgTime: '',
		orderMsgaddressNote: '',
		orderMsgTimeNote: '',
		styleList: ['noSelect_style', 'noSelect_style', 'noSelect_style', 'noSelect_style', 'noSelect_style', 'noSelect_style'],
		type: '1', //订单类型  1 自提  2外卖
		timeSelfDefined: false, //是否显示自定义事件
		addrSelfDefined: false, //是否显示地址
		timeWay: 0, //0 固定时间 1自定义事件
		zitiStyle: 'menu_select', //自提样式
		sendStyle: 'menu_unselect', //外卖样式
		pickerAddress:'', //选择地方
		pickerTime:'',   //选择时间
		selfPickLunckTime:'',//晚餐
		selfPickDinnerTime:'', //午餐
		newTimeArr:'', //新的时间数组
		newTimeStemp:null,//新的时间戳
		// newAddressString:getApp().globalData.common.reserveShopName
		

	},

	onLoad: function(options) {
		// this.setData({
		// 	addressString:this.data.newAddressString
		// })
	},

	onReady: function() {
		console.log('onReady')
	},
	onShow: function() {
		console.log('reserveShopCode******'+getApp().globalData.common.reserveShopCode)
		console.log('reserveShopName******'+getApp().globalData.common.reserveShopName)
		this.setData({
			addressString:getApp().globalData.common.reserveShopName
		})
		this.getShopInfo(2);
		let pages = getCurrentPages();
		let currPage = pages[pages.length - 1];
		this.setData({
			addressId: currPage.data.aId ? currPage.data.aId : ""
		});
		// console.log( this.data.addressId);
		console.log(this.data.addressId);
		this.canPay = true;
		//获取昵称
		if (getApp().globalData.userInfo.nickName == '亲') {

			this.setData({
				isNeedwx: true
			})

		}


		var badd = getApp().globalData.common.reservebAdd || '';
		var sadd = getApp().globalData.common.reservesAdd || '';
		var add = getApp().globalData.common.reserveSelfAdd || '';
		//console.log('badd=' + badd)
		//console.log('sadd=' + sadd)
		//console.log('add' + getApp().globalData.common.reserveSelfAdd)
		 this.setData({
		// 	chooseAddress: badd + sadd,
		 	chooseNote: getApp().globalData.common.reservesNote,
		// 	addressString: add
		 })
		 
		this.getqianyueType();
		//console.log(getApp().globalData.common.reserveVid)
		if (getApp().globalData.common.reserveVid == null) {
			this.getShopMarket();
		} else {
			this.getShopMarket(getApp().globalData.common.reserveVid);
		}
		this.getAllAddress();
	},
	onHide: function() {},
	onUnload: function() {

	},
	addressPickerAction:function(){
		
      this.setData({
      	showFloat:true,
        pickerAddress: this.data.newAddressArr[0].shopName,
      	showAddressPick:true
      })
	},
	//获取所有字体地址
	getAllAddress:function(){
			wx.showLoading({
			title: '加载中',
			mask: true
		});
		var _self = this;
		console.log("memId------" + getApp().globalData.userInfo.memId);
		wx.getLocation({
			type: 'gcj02',
			success: function (res) {
				var latitude = res.latitude
				var longitude = res.longitude
				var speed = res.speed
				var accuracy = res.accuracy
				console.log("________" + getApp().globalData.userInfo.memId);
				// var _self = this;
				wx.request({
					url: getApp().globalData.baseUrl + '/applet/reserve/shopsOfSaleOut.do',
					data: {
						shopCode: getApp().globalData.common.reserveShopCode,
						x: longitude,
						y: latitude
					},
					header: getApp().globalData.header,
					success: function(res) {
						wx.hideLoading();
						if (res.data.code == 200) {
							console.log('获取自提点成功')
							console.log(res)
							_self.setData({
								newAddressArr:res.data.obj
							})
						}
						//console.log(res)
					}
				})
			},
			fail: function () {
				wx.hideLoading();
				console.log("失败")
			
			}
		})
        
	},
	bindChangeAddress:function(e){
		console.log(e.detail.value)
		console.log(this.data.newAddressArr[e.detail.value].shopName)
       this.setData({
			pickerAddress: this.data.newAddressArr[e.detail.value].shopName
		})
	},
	//关闭地址选择
	cancelAddressAction:function(){
        this.setData({
        	showAddressPick:false,
        	showFloat:false
        })
	},
	//选择地址选择
	makeAddressAction:function(){
        this.setData({
        	addressString:this.data.pickerAddress,
        	showAddressPick:false,
        	showFloat:false
        })
	},
	chooseWay: function(e) {
		//console.log(e.currentTarget.dataset.code)
		var code = e.currentTarget.dataset.code;
		if (code == 10) {
			this.setData({
				type: 1
			})
			this.setData({
				zitiStyle: 'menu_select',
				sendStyle: 'menu_unselect'
			})
		} else {
			this.setData({
				type: 2
			})
			this.setData({
				zitiStyle: 'menu_unselect',
				sendStyle: 'menu_select'
			})
			this.getUserAddress();

		}
	},
	getUserAddress: function() {
		var _self = this;
		wx.request({
			url: getApp().globalData.baseUrl + '/applet/address/getDefaultAddress.do',
			data: {
				shopCode: getApp().globalData.common.reserveShopCode,
			},
			header: getApp().globalData.header,
			success: function(res) {
				if (res.data.code == 200) {
					getApp().globalData.common.reservebAdd = res.data.obj.addressFixed;
					getApp().globalData.common.reservesAdd = res.data.obj.addressDetail;
					_self.setData({
						chooseAddress: res.data.obj.addressFixed + res.data.obj.addressDetail

					})
				}
				//console.log(res)
			}
		})
	},
	chooseType: function(e) {
		this.setData({
			timeWay: e.currentTarget.dataset.type
		})

		this.fitShowTime();
		var arr = []
		this.setData({
			chooseTime: arr
		})
		var leftStyle = (750 / this.data.timeType.length - 100) / 2 + (750 * e.currentTarget.dataset.type / this.data.timeType.length) + 'rpx';
		this.setData({
			leftStyle: leftStyle
		})

		if (e.currentTarget.dataset.type == 0) {
			this.setData({
				timeType: this.getTimeType(this.data.timeSelfDefined, 0)

			})

			var dataArr, hourArr;
			var showTimeArr = this.fitArr(this.data.shopInfo.fixedTime);
			if (showTimeArr.length == 0) {
				dataArr = ['明天'];
				hourArr = this.data.shopInfo.fixedTime;
			} else {
				dataArr = ['今天'];
				hourArr = showTimeArr;
			}
			this.setData({
				pickerArr: [{
					'timeArr': dataArr
				}, {
					'timeArr': hourArr
				}]
			})
		} else if (e.currentTarget.dataset.type == 1) {
			this.setData({
				timeType: this.getTimeType(this.data.timeSelfDefined, 1)
			})
			var startTime;
			var endTime;
			startTime = this.data.shopInfo.distributionStartTime;
			endTime = this.data.shopInfo.distributionEndTime;
			var startTimeHours = parseInt(startTime.split(':')[0]);
			var startMinutes = parseInt(startTime.split(':')[1]);
			var endTimeHours = parseInt(endTime.split(':')[0]);
			var endMinutes = parseInt(endTime.split(':')[1]);
			var hourArr = [];
			var minuteArr = [];
			var oDate = new Date();
			var hour = parseInt(oDate.getHours()) //当前小时
			var minute = parseInt(oDate.getMinutes()) //当前分钟
			if (hour > endTimeHours) {
				for (var i = startTimeHours; i <= endTimeHours; i++) {

					hourArr.push(i + '点')
				}
				for (var i = startMinutes; i <= 11; i++) {

					minuteArr.push(i * 5 + '分')


				}
				this.setData({
					pickerArr: [{
						'timeArr': ['明天']
					}, {
						'timeArr': hourArr
					}, {
						'timeArr': minuteArr
					}]
				})

			} else {

				if (hour > startTimeHours) {
					startTimeHours = startTimeHours;
					startMinutes = startMinutes;
				} else if (hour < startTimeHours) {
					startTimeHours = startTimeHours;
					startMinutes = startMinutes;
				} else if (hour == startTimeHours) {
					startTimeHours = startTimeHours;
					startMinutes = startMinutes > minute ? startMinutes : minute;
				}
				for (var i = startTimeHours; i <= endTimeHours; i++) {
					if (i >= hour) {
						hourArr.push(i + '点')
					}

				}

				for (var i = 0; i <= 11; i++) {
					var str = ''
					if (i * 5 < 10) {
						str = '0' + i * 5 + "分"
					} else {
						str = i * 5 + "分"
					}
					minuteArr.push(str)
				}
				this.setData({
					pickerArr: [{
						'timeArr': ['今天', '明天']
					}, {
						'timeArr': hourArr
					}, {
						'timeArr': minuteArr
					}]

				})

			}
		}
	},

    //选择时间按钮
	timePickerAction: function() {
       console.log('选择时间');
       var oDate = new Date();
	   var hour = parseInt(oDate.getHours()) //当前小时
	   var minute = parseInt(oDate.getMinutes()); //当前分钟
       console.log('当前小时:'+hour);
       console.log('当前分钟:'+minute);
       var nowNum=hour*60+minute;
       console.log(this.data.shopInfo.secondOffTime)
       console.log(this.data.shopInfo.firstOffTime)
       var firstTime=null;
       var secondTime=null;
       if (this.data.shopInfo.firstOffTime!='') {
       	firstTime=this.data.shopInfo.firstOffTime.split(':')[0]*60+this.data.shopInfo.firstOffTime.split(':')[1]*1
       }
       if (this.data.shopInfo.secondOffTime!='') {
       	secondTime=this.data.shopInfo.secondOffTime.split(':')[0]*60+this.data.shopInfo.secondOffTime.split(':')[1]*1;
       }
       console.log("firstTime="+firstTime)
       console.log('secondTime='+secondTime)
       

       //没有晚餐
       if (!secondTime) {
           if (nowNum>firstTime) {
               var arr=['明日午餐--'+this.data.selfPickLunckTime];
		       	   this.setData({
		       	   	newTimeArr:arr
		       	
		       	   })
           }else{
           	 var arr=['今日午餐--'+this.data.selfPickLunckTime];

	       	   this.setData({
	       	   	newTimeArr:arr
	       	
	       	   })

           }

       }else{


	       	if (nowNum>secondTime||nowNum==secondTime) {  //17:30之后之后只能定明天的
	       	   var arr=['明日午餐--'+this.data.selfPickLunckTime,'明日晚餐--'+this.data.selfPickDinnerTime];

	       	   this.setData({
	       	   	newTimeArr:arr
	       	
	       	   })
	       }else if(nowNum<=firstTime){  //10:30之前定今天的
	           var arr=['今日午餐--'+this.data.selfPickLunckTime,'今日晚餐--'+this.data.selfPickDinnerTime];
	       	   this.setData({
	       	   	newTimeArr:arr
	       	   })

	       }else if (nowNum>firstTime&&nowNum<secondTime) {  //10:30之后定17点30之前
	       	  var arr=['今日晚餐--'+this.data.selfPickDinnerTime,'明日午餐--'+this.data.selfPickLunckTime];
	       	   this.setData({
	       	   	newTimeArr:arr
	       	   })
	       }
   
       }
      


       
       

		this.setData({
			showTimePick: true,
			showFloat: true,
			pickerTime:this.data.newTimeArr[0]
			// timeString:this.data.newTimeArr[0]
		})

	},
	payPickerAction: function() {
		this.setData({
			showPayPick: true,
			showFloat: true
		})
	},
	bindChange: function(e) {
        
        console.log(e.detail.value)
        console.log()

        this.setData({
        	pickerTime:this.data.newTimeArr[e.detail.value]
        })
        return

		this.setData({
			timeType: this.getTimeType(this.data.timeSelfDefined, 0)
		})
		this.setData({
			chooseTime: e.detail.value
		})

		return;

		var arr = this.data.pickerArr[0];
		var ind = e.detail.value[0];

		//console.log("****====")
		//console.log(this.data.timeWay)
		//console.log(arr.timeArr[ind])


		//console.log(e.detail.value)
		//console.log(this.data.pickerArr)
		if (this.data.pickerArr.length == 2 && e.detail.value.length == 3) {
			e.detail.value = [0, this.data.pickerArr[1].timeArr.length - 1]
			this.setData({
				chooseTime: e.detail.value,

			})
		}
		if (this.data.pickerArr.length == 3 && e.detail.value.length == 2) {
			e.detail.value = [0, 0, 0]
			this.setData({
				chooseTime: e.detail.value
			})
		}

		for (var i = 0; i < this.data.pickerArr.length; i++) {
			var indd = e.detail.value[i];
			var arrr = this.data.pickerArr[i];
			if (!arrr.timeArr[indd]) {
				e.detail.value[i] = 0
			}
		}
		//console.log('修改储存之前')
		//console.log(e.detail.value)
		this.setData({
			chooseTime: e.detail.value
		})

		//console.log('修改储存状态')
		//console.log(e.detail.value)
		if (this.data.timeWay == 0) { //固定时间

			this.setData({
				timeType: this.getTimeType(this.data.timeSelfDefined, 0)
			})

			var dataArr, hourArr;
			var showTimeArr;
			showTimeArr = this.fitArr(this.data.shopInfo.fixedTime);
			if (showTimeArr.length == 0) {
				dataArr = ['明天'];
				hourArr = this.data.shopInfo.fixedTime;
			} else {
				dataArr = ['今天', '明天'];
				hourArr = showTimeArr;
			}

			if (arr.timeArr[ind] == '今天') {
				hourArr = this.fitArr(this.data.shopInfo.fixedTime);
			} else if (arr.timeArr[ind] == '明天') {
				hourArr = this.data.shopInfo.fixedTime;
			}
			this.setData({
				pickerArr: [{
					'timeArr': dataArr
				}, {
					'timeArr': hourArr
				}]

			})


		} else if (this.data.timeWay == 1) { //自定义时间
			this.setData({
				timeType: this.getTimeType(this.data.timeSelfDefined, 1)
			})
			var startTime;
			var endTime;
			startTime = this.data.shopInfo.distributionStartTime;
			endTime = this.data.shopInfo.distributionEndTime;
			var startTimeHours = parseInt(startTime.split(':')[0]);
			var startMinutes = parseInt(startTime.split(':')[1]);
			var endTimeHours = parseInt(endTime.split(':')[0]);
			var endMinutes = parseInt(endTime.split(':')[1]);
			var hourArr = [];
			var minuteArr = [];
			var oDate = new Date();
			var hour = parseInt(oDate.getHours()) //当前小时
			var minute = parseInt(oDate.getMinutes()); //当前分钟



			if (arr.timeArr[ind] == '明天') {
				if (hour > endTimeHours) {
					for (var i = startTimeHours; i <= endTimeHours; i++) {

						hourArr.push(i + '点')
					}
					for (var i = startMinutes; i <= 11; i++) {
						minuteArr.push(i * 5 + '分')
					}
					this.setData({
						pickerArr: [{
							'timeArr': ['明天']
						}, {
							'timeArr': hourArr
						}, {
							'timeArr': minuteArr
						}]
					})

				} else {

					for (var i = startTimeHours; i <= endTimeHours; i++) {

						hourArr.push(i + '点')
					}
					for (var i = startMinutes; i <= 11; i++) {
						minuteArr.push(i * 5 + '分')
					}
					this.setData({
						pickerArr: [{
							'timeArr': ['今天', '明天']
						}, {
							'timeArr': hourArr
						}, {
							'timeArr': minuteArr
						}]
					})

				}
				return;
			}

			if (hour > endTimeHours) {
				for (var i = startTimeHours; i <= endTimeHours; i++) {

					hourArr.push(i + '点')
				}
				for (var i = startMinutes; i <= 59; i++) {
					minuteArr.push(i + '分')
				}
				this.setData({
					pickerArr: [{
						'timeArr': ['明天']
					}, {
						'timeArr': hourArr
					}, {
						'timeArr': minuteArr
					}]
				})

			} else {

				if (hour > startTimeHours) {
					startTimeHours = startTimeHours;
					startMinutes = startMinutes;
				} else if (hour < startTimeHours) {
					startTimeHours = startTimeHours;
					startMinutes = startMinutes;
				} else if (hour == startTimeHours) {
					startTimeHours = startTimeHours;
					startMinutes = startMinutes > minute ? startMinutes : minute;
				}
				for (var i = startTimeHours; i <= endTimeHours; i++) {
					if (i >= hour) {
						hourArr.push(i + '点')
					}
				}
				for (var i = 0; i <= 11; i++) {
					var str = ''
					if (i * 5 < 10) {
						str = '0' + i * 5 + "分"
					} else {
						str = i * 5 + "分"
					}
					minuteArr.push(str)
				}
				this.setData({
					pickerArr: [{
						'timeArr': ['今天', '明天']
					}, {
						'timeArr': hourArr
					}, {
						'timeArr': minuteArr
					}]
				})

			}

		}



	},
	cancelTimeAction: function() {
		this.setData({
			showTimePick: false,
			showFloat: false
		})
	},
	makeTimeAction: function() {
		// console.log(this.data.pickerArr)
		// var chooseTimes;
		// if (this.data.pickerArr.length == 2) {
		// 	var times;
		// 	var datas;
		// 	if (this.data.chooseTime.length == 0) {
		// 		times = this.data.pickerArr[1].timeArr[0];
		// 		datas = this.data.pickerArr[0].timeArr[0];
		// 	} else {
		// 		datas = this.data.pickerArr[0].timeArr[this.data.chooseTime[0]];
		// 		times = this.data.pickerArr[1].timeArr[this.data.chooseTime[1]];

		// 	}
		// 	console.log("2")
		// 	console.log(times)

		// 	var timestamp = Date.parse(new Date());
		// 	var date = new Date(timestamp);
		// 	//获取小时  
		// 	var H =date.getHours();
		// 	//获取分钟  
		// 	var M = date.getMinutes();
		// 	console.log(times.split(":")[0]*60)
		// 	console.log(times.split(":")[1]*1)
		// 	if ((times.split(":")[0]*60+times.split(":")[1]*1)<(H*60+M*1)) {
		// 		this.showMyToast(this, '请选择当前时间之后自提')
		// 		return
		// 	}
			

		// 	chooseTimes = times;
		// 	// chooseTimes = this.fitTime(parseInt(times.split(':')[0]), parseInt(times.split(':')[1]), datas);

		// } else if (this.data.pickerArr.length == 3) {
		// 	var hours, minutes, datas;
		// 	if (this.data.chooseTime.length == 0) {
		// 		datas = this.data.pickerArr[0].timeArr[0];
		// 		hours = this.data.pickerArr[1].timeArr[0];
		// 		minutes = this.data.pickerArr[2].timeArr[0];
		// 	} else {
		// 		datas = this.data.pickerArr[0].timeArr[this.data.chooseTime[0]];
		// 		hours = this.data.pickerArr[1].timeArr[this.data.chooseTime[1]];
		// 		minutes = this.data.pickerArr[2].timeArr[this.data.chooseTime[2]];

		// 	}
		// 	console.log("3")
		// 	console.log(times)
		// 	chooseTimes = times;
		// 	// chooseTimes = this.fitTime(parseInt(hours), parseInt(minutes), datas);

		// }
		// console.log("chooseTimes" + chooseTimes)
		// if (chooseTimes) {

		// 	var str = ''
		// 	if (this.data.chooseTime.length == 0) {
		// 		var str = '';
		// 		//console.log("****++++")
		// 		//console.log(this.data.pickerArr)
		// 		for (var i = 0; i < this.data.pickerArr.length; i++) {
		// 			str += this.data.pickerArr[i].timeArr[0];
		// 		}
		// 	} else {
		// 		for (var i = 0; i < this.data.pickerArr.length; i++) {
		// 			str += this.data.pickerArr[i].timeArr[this.data.chooseTime[i]];

		// 		}
		// 	}

		// 	console.log(str);
		// 	if (this.data.type == '2') {
		// 		this.setData({
		// 			peisongTime: str,
		// 			chooseTimes: chooseTimes

		// 		})
		// 	} else if (this.data.type == '1') {
		// 		this.setData({
		// 			timeString: str,
		// 			getTimes: chooseTimes

		// 		})
		// 	}
		// } else {

		// }
		// var e = {
		// 	currentTarget: {
		// 		dataset: {
		// 			type: 0
		// 		}
		// 	}
		// }
		//this.chooseType(e)
		this.setData({
			timeString:this.data.pickerTime
		})
		this.cancelTimeAction();

	},
	cancelPayAction: function() {
		this.setData({
			showFloat: false,
			showPayPick: false
		})
	},
	
	getShopInfo: function(type) {
		var _self = this;
		wx.showLoading({
			title: '加载中',
		})
		wx.request({
			url: getApp().globalData.baseUrl + '/applet/reserve/getShopSettings.do',
			data: {
				shopCode: getApp().globalData.common.reserveShopCode,
				type: type
			},
			header: getApp().globalData.header,
			success: function(res) {
				wx.hideLoading()
				if (res.data.code != 200) {
					return
				}
				var dataArr, hourArr;
				var showTimeArr = _self.fitArr(res.data.obj.fixedTime);
				dataArr = ['今天'];
				hourArr = res.data.obj.fixedTime;
				console.log(hourArr);
				
				_self.setData({
					timeType: _self.getTimeType(res.data.obj.timeSelfDefined, 0),
					timeSelfDefined: res.data.obj.timeSelfDefined,
					addrSelfDefined: res.data.obj.addrSelfDefined,
					selfPickLunckTime:res.data.obj.selfPickLunckTime,//晚餐
		            selfPickDinnerTime:res.data.obj.selfPickDinnerTime, //午餐
					shopInfo: res.data.obj,
					// addressString:res.data.obj.distributionAddress[0],
					pickerArr: [{
						'timeArr': dataArr
					}, {
						'timeArr': hourArr
					}]
				})
				console.log(res.data.obj.distributionAddress[0].length);
				//if(_self.strlen(res.data.obj.shopAddress)>60){
				if(res.data.obj.distributionAddress[0].length>=32){
					_self.setData({
						addStyle:"address-wrapper",
						heightStyle:"heightStyle"
					});
				}else{
					_self.setData({
						//addStyle:"time-wrapper",
						addStyle:"address-wrapper1",
						heightStyle:"heightStyle1"
					});
				}
				if (!res.data.obj.timeSelfDefined) {
					_self.setData({
						leftStyle: '325rpx'
					})
				} else {
					_self.setData({
						leftStyle: '137.5rpx'
					})
				}
				if (type == 1) {

				} else {
					_self.fitShowTime();
				}


			}
		})

	},
	strlen(str){
		var len = 0;
		for (var i=0; i<str.length; i++) {
			 var c = str.charCodeAt(i);
			 //单字节加1
			 if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) {
					  len++;
			 }else {
					 len+=2;
			 }
		}
		return len;
	},
	getShopMarket: function(id) {
		console.log("****&&&***")
		console.log("id==" + id)
		console.log("****&&&***")
		var _self = this;
		wx.showLoading({
			title: '加载中',
		})
		var url = '';
		var json;


		if (id == null) {
			console.log('没有');
			url = '/applet/reserve/cart/cart-settle.do',
				json = {
					shopCode: getApp().globalData.common.reserveShopCode,
					type: 2
				}


		} else {
			console.log('有')
			url = '/applet/reserve/cart/order-settle.do',
				json = {
					shopCode: getApp().globalData.common.reserveShopCode,
					voucherMemberId: id,
					type: 2
				}

		}
		wx.request({
			url: getApp().globalData.baseUrl + url,
			data: json,
			header: getApp().globalData.header,
			success: function(res) {
				wx.hideLoading()
				if (res.data.code == 200) {
					_self.setData({
						shopMarket: res.data.obj
					})
					if (res.data.obj.autoFlag == 1) {
						getApp().globalData.common.reserveVid = null
					} else {
						getApp().globalData.common.reserveVid = res.data.obj.voucherMemberId;
					}
					console.log(res.data.obj.voucherMemberId)
					_self.getBalance();
				} else if (res.data.code == 508) {
					wx.showModal({
						title: '提示',
						showCancel: false,
						content: res.data.des + '库存不足,请返回购物车重新选择',
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定')
								wx.navigateBack({
									delta: 0
								})

							} else if (res.cancel) {
								console.log('用户点击取消')
							}
						}
					})


					_self.setData({
						shopMarket: res.data.obj
					})
					if (res.data.obj.autoFlag == 1) {
						getApp().globalData.common.reserveVid = null
					} else {
						getApp().globalData.common.reserveVid = res.data.obj.voucherMemberId;
					}

					console.log(res.data.obj.voucherMemberId)
					_self.getBalance();
				} else {
					wx.showToast({
						title: '服务器异常',
						icon: 'none',
						duration: 2000,
						mask: true,
						'success': function() {

						}
					})

				}

			}
		})

	},
	getBalance: function() {
		var _self = this;
		wx.request({
			url: getApp().globalData.baseUrl + '/wxappletMember/getBalance.do',
			data: {
				shopCode: getApp().globalData.common.reserveShopCode,
			},
			header: getApp().globalData.header,
			success: function(res) {
				if (res.data.code == 200) {
					if (parseFloat(res.data.obj.balance) < parseFloat(_self.data.shopMarket.promotionPrice)) {
						_self.setData({
							payText: "微信",
							balance: res.data.obj.balance,
							payType: 11
						})

					} else {
						_self.setData({
							payText: "余额:" + res.data.obj.balance,
							balance: res.data.obj.balance,
							payType: 4
						})
					}
				}
				console.log(res)
			}
		})
	},
	hideOrder: function() {
		this.setData({
			showFloat: false,
			showOrdermsg: false,
			showTimePick: false, //是否显示时间
			showAddressPick:false,//显示地址
			showPayPick: false //是否显示支付渠道

		})

	},
	//去选择优惠券
	goSelect: function() {
		console.log(this.data.shopMarket)
		if (this.data.shopMarket.autoFlag == 1) {

			return
		}
		wx.navigateTo({
			url: `../reserveCoupon/reserveCoupon?voucherMemberId=${this.data.shopMarket.voucherMemberId}`
		})
	},
	formSubmit: function(e) {
		console.log("e.detail.formId");
		console.log(e.detail.formId);
		this.setData({
			formId: e.detail.formId
		})
		this.payAction();
	},
	payAction: function() {
       

		console.log(this.canPay)
		if (!this.canPay) {
			return
		}
		var distributionType, orderMsgaddress, orderMsgTime, orderMsgaddressNote, orderMsgTimeNote;
		if (this.data.type == '2') {
			distributionType = 20
			// if (!this.data.chooseTimes) {
			// 	this.showMyToast(this, '请选择配送时间')
			// 	return;
			// }
			var oDate = new Date();
			var timeS = oDate.toLocaleDateString() + " " + 10 + ":" + 30;
			console.log(timeS)
			console.log(typeof(timeS));
			timeS = timeS.replace(/·/g, "");
			console.log("timeS" + timeS);
			console.log(Date.parse(timeS));
			timeS = Date.parse(timeS);
			// return timeS


			this.setData({
				chooseTimes:timeS/1000
			})
			// this.data.chooseTimes
			orderMsgaddress = '配送地址';
			orderMsgTime = '配送时间';
			orderMsgaddressNote = this.data.chooseAddress;
			orderMsgTimeNote = this.data.peisongTime;

		} else if (this.data.type == '1') {
			distributionType = 10;
			var timeAA=0;
			console.log(this.data.timeString)
			if (this.data.timeString=='请选择') {
				this.showMyToast(this, '请选择配送时间')
				return
			}else{
             
               var startTime=this.data.timeString.split('--')[1].split('~')[0]
               var h = parseInt(startTime.split(':')[0]);
	           var m = parseInt(startTime.split(':')[1]);
               if (this.data.timeString.indexOf('明日')>-1) {
                    timeAA=this.fitTime(h,m)+24*60*60*1000;
               }else{
               	    timeAA=this.fitTime(h,m);
               }
               
			}

			



			this.setData({
				getTimes:timeAA
			})
			orderMsgaddress = '自提地址';
			orderMsgTime = '自提时间';
			orderMsgaddressNote = this.data.addressString;
			orderMsgTimeNote = this.data.timeString;

		}

		this.setData({
			//orderMsgaddress: orderMsgaddress,
			orderMsgaddress: this.data.addressString,
			orderMsgTime: orderMsgTime,
			orderMsgaddressNote: orderMsgaddressNote,
			orderMsgTimeNote: orderMsgTimeNote
		})

		if (this.data.addressString=='请选择') {
        	 this.showMyToast(this, '请选择配送地点')
			 return;
        }
        console.log('this.data.getTimes')
        console.log(this.data.getTimes)
        if (!this.data.getTimes) {
        	 this.showMyToast(this, '请选择配送地点')
			 return;
        }
		this.canPay = false;
		this.payMakersure();

	},
	payMakersure: function() {
         

      

		if (this.data.payType == '4' && this.data.balanceP) {
			this.setData({
				isShow: true,
				styleList: [
					'noSelect_style',
					'noSelect_style',
					'noSelect_style',
					'noSelect_style',
					'noSelect_style',
					'noSelect_style'
				],
				showOrdermsg: false

			})
			return
		} else {
			this.creatOrder();
		}

		this.setData({
			showFloat: false,
			showOrdermsg: false
		})



	},
	creatOrder: function() {
		var distributionType, address, time, detailAddress;
		if (this.data.type == '2') {
			distributionType = 20;
			//address = getApp().globalData.common.reservebAdd;
			//detailAddress = getApp().globalData.common.reservesAdd
			time = this.data.chooseTimes;
			//if (!getApp().globalData.common.reservebAdd || !this.data.chooseTimes) { 
			if (!this.data.chooseTimes) { 
				this.showMyToast(this, '请选择配送时间')
				return;
			}
		} else if (this.data.type == '1') {
			distributionType = 10;
			address = this.data.orderMsgaddressNote;
			detailAddress = getApp().globalData.common.reserveSelfAdd
			time = this.data.getTimes;

		}
 
       
		var orderInfo = {
			shopCode: getApp().globalData.common.reserveShopCode,
			voucherMemberId: getApp().globalData.common.reserveVid,
			distributionType: distributionType,
			//address: address,
			address: this.data.addressString,
			distributionTime: time,
			//deliveryTime: time,
			detailAddress: detailAddress,
			remark: getApp().globalData.common.reservesNote,
			type: 2,
			formId: this.data.formId
		}

		var _self = this;
		wx.showLoading({
			title: '加载中',
			mask: true
		})
		wx.request({
			url: getApp().globalData.baseUrl + '/applet/order/v2/createGoodsOrder.do',
			method: 'post',
			data: orderInfo,
			header: getApp().globalData.header,
			success: function(res) {
				console.log(res)
				wx.hideLoading();
				if (res.data.code == 200) {
					getApp().globalData.common.reserveVid = null;
					getApp().globalData.common.reservesNote = null;
					getApp().globalData.common.reservebAdd = null;
					getApp().globalData.common.reservesAdd = null;
					getApp().globalData.common.reserveSelfAdd = null;
					_self.pay(res.data.obj, _self.data.payType);

				} else if (res.data.code == 508) {
					wx.showModal({
						title: '提示',
						showCancel: false,
						content: '库存不足,请返回购物车重新选择',
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定')
								wx.navigateBack({
									delta: 0
								})

							} else if (res.cancel) {
								console.log('用户点击取消')
							}
						}
					})
				} else {
					_self.canPay = true;
					wx.showToast({
						title: res.data.des,
						icon: 'none',
						duration: 2000,
						mask: true,
						'success': function() {

						}
					})
				}
			}

		})
	},
	pay: function(code, type) {
		wx.showLoading({
			title: '加载中',
			mask: true
		})
		wx.request({
			url: getApp().globalData.baseUrl + '/applet/pay/v1/pay.do?orderCode=' + code + "&payType=" + type,
			method: 'post',
			header: getApp().globalData.header,
			success: function(res) {
				wx.hideLoading();
				if (res.data.code == 200) {
					if (type == "4") {
						wx.redirectTo({
							url: '/pages/reserveOrder/reserveOrder?code=' + res.data.obj.orderCode
							// url: `../fulfil/fulfil?type=1&orderCode=${res.data.obj.orderCode}&discountPrice=${res.data.obj.discountPrice}&orderPrice=${res.data.obj.orderPrice}`
						})
						return
					}
					if (res.data.obj.status == "2") {
						wx.redirectTo({
							url: '../orders/orders?current=0'
						})
						return
					}
					if (res.data.obj.type == '0') {
						console.log("非免密支付");
						wx.requestPayment({
							'timeStamp': res.data.obj.timeStamp,
							'nonceStr': res.data.obj.nonceStr,
							'package': res.data.obj.prepay_id,
							'signType': res.data.obj.signType,
							'paySign': res.data.obj.paySign,
							'success': function(response) {

								// wx.switchTab({     url:'../mine/mine' })
								wx.redirectTo({
									url: '/pages/reserveOrder/reserveOrder?code=' + res.data.obj.orderCode
									// url: `../fulfil/fulfil?type=1&orderCode=${res.data.obj.orderCode}&discountPrice=${res.data.obj.discountPrice}&orderPrice=${res.data.obj.orderPrice}`
								})
							},
							'fail': function(res) {

								wx.redirectTo({
									url: '../orders/orders?current=0'
								})
							}
						}) // 支付方式为余额支付时

					} else if (res.data.obj.type == '1') {
						console.log("免密支付")
						wx.redirectTo({
							url: '/pages/reserveOrder/reserveOrder?code=' + res.data.obj.orderCode
							// url: `../fulfil/fulfil?type=1&orderCode=${res.data.obj.orderCode}&discountPrice=${res.data.obj.discountPrice}&orderPrice=${res.data.obj.orderPrice}`
						})
					}

				} else {
					console.log("支付失败")
					wx.redirectTo({
						url: '../orders/orders?current=0'
					})
				}
			}

		})


	},
	choosePatType: function(e) {
		console.log(e.currentTarget.dataset.code);
		var code = e.currentTarget.dataset.code

		if (code == '0') {
			if (this.data.balance < this.data.shopMarket.promotionPrice) {
				this.setData({
					payType: "11",
					payText: "微信"
				})


			} else {
				this.setData({
					payType: "4",
					payText: "余额:" + this.data.balance,
				})

			}
		} else if (code == '1') {

			this.setData({
				payType: "11",
				payText: "微信"
			})


		}
		this.cancelPayAction();

	},

	fitTime: function(h, m, n) {

		var startTime;
		var endTime;
		startTime = this.data.shopInfo.distributionStartTime;
		endTime = this.data.shopInfo.distributionEndTime;
		var startTimeHours = parseInt(startTime.split(':')[0]);
		var startMinutes = parseInt(startTime.split(':')[1]);
		var endTimeHours = parseInt(endTime.split(':')[0]);
		var endMinutes = parseInt(endTime.split(':')[1]);
		var start = startTimeHours * 60 + startMinutes;
		var end = endTimeHours * 60 + endMinutes;

		var now = h * 60 + m;
		var oDate = new Date();

		var timeS = oDate.toLocaleDateString() + " " + h + ":" + m;
		console.log(timeS)
		console.log(typeof(timeS));
		timeS = timeS.replace(/·/g, "");
		console.log("timeS" + timeS);
		console.log(Date.parse(timeS));
		timeS = Date.parse(timeS);
		return timeS
		return;
		console.log('****');
		console.log(h, m, n);
		console.log('=====');

		var startTime;
		var endTime;
		startTime = this.data.shopInfo.distributionStartTime;
		endTime = this.data.shopInfo.distributionEndTime;
		var startTimeHours = parseInt(startTime.split(':')[0]);
		var startMinutes = parseInt(startTime.split(':')[1]);
		var endTimeHours = parseInt(endTime.split(':')[0]);
		var endMinutes = parseInt(endTime.split(':')[1]);
		var start = startTimeHours * 60 + startMinutes;
		var end = endTimeHours * 60 + endMinutes;
		var now = h * 60 + m;

		var oDate = new Date();
		//时  
		var oDateh = oDate.getHours();
		//分  
		var oDatemin = oDate.getMinutes();

		var oDateNow = oDateh * 60 + oDatemin; //当前时间
		if (oDateNow > now && n == '今天') {

			this.showMyToast(this, '请选择合适的配送时间')
			return false;
		} else {
			if (start < now && now < end || now == end || now == start) {
				var oDate = new Date();
				var timeS = oDate.toLocaleDateString() + " " + h + ":" + m;
				console.log(Date.parse(timeS))
				timeS = Date.parse(timeS);
				if (n == '今天') {

				} else if (n == '明天') {

					timeS += 24 * 60 * 60 * 1000;
				}
				return timeS
			} else {
				this.showMyToast(this, '请选择合适的配送时间')
				return false;
			}
		}



	},
	showMyToast: function(self, my_toast_tip, time = 1000, template = 'my_toast') {
		self.setData({
			template: template, //my_toast
			my_toast_tip: my_toast_tip
		})
		var timer = setTimeout(() => {
			self.setData({
				template: '', //my_toast
				my_toast_tip: ''
			})
			clearTimeout(timer);
		}, time)

	},
	maixiangTurn: function() {
		var mxUrl = '../maixiang/maixiang';

		getApp().globalData.common.mxShopCode = getApp().globalData.common.reserveShopCode;
		wx.navigateTo({
			url: mxUrl
		})

	},
	fitShowTime: function() {
		var startTime;
		var endTime;
		startTime = this.data.shopInfo.selfDistributionStartTime;
		endTime = this.data.shopInfo.selfDistributionEndTime;
		this.setData({
			timeNote: {
				start: startTime,
				end: endTime
			}

		})
	},
	//获取签约状态
	getqianyueType: function() {
		var _self = this;
		wx.request({
			url: getApp().globalData.baseUrl + '/applet/freepay/v3/sign/state.do',
			method: 'get',
			header: getApp().globalData.header,
			success: function(res) {
				console.log(res)
				if (res.data.obj.BALANCE == 0) {
					_self.setData({
						balanceP: true
					})
				} else {
					_self.setData({
						balanceP: false
					})
				}


			}

		})
	},
	//密码
	getPassWord: function(e) {
		var _self = this;
		console.log(e.detail.value.length)

		var arr = _self.data.styleList
		for (var i = 0; i < 6; i++) {
			if (i <= e.detail.value.length - 1) {

				arr[i] = 'select_style'
			} else {
				arr[i] = 'noSelect_style'
			}
		}
		if (e.detail.value.length == 6) {
			console.log("*****输入密码成功*****")
			_self.filterPassword(e.detail.value);
		}
		_self.setData({
			styleList: arr
		})
		console.log(_self.data.styleList)


	},
	hideView: function() {
		this.setData({
			input_type: true
		})

	},
	closeView: function() {
		this.canPay = true;
		this.setData({
			showFloat: false,
			isShow: false,
			balanceStatus: false,
			styleList: ['noSelect_style', 'noSelect_style', 'noSelect_style', 'noSelect_style', 'noSelect_style', 'noSelect_style']

		})
	},
	filterPassword: function(num) {
		var _self = this;
		wx.request({
			url: getApp().globalData.baseUrl + '/applet/balance/pwd/check.do?password=' + num,
			method: 'post',
			header: getApp().globalData.header,
			success: function(res) {
				if (res.data.code == 200) {
					console.log("调用支付");
					// _self.pay(_self.data.orderCode, 4)
					_self.creatOrder();
					_self.setData({
						balanceStatus: true
					})
				} else {
					_self.setData({
						balanceStatus: false,
						isShow: false,
						styleList: ['noSelect_style', 'noSelect_style', 'noSelect_style', 'noSelect_style', 'noSelect_style', 'noSelect_style']
					})
					fetch.showMyToast(_self, "密码错误")
					_self.canPay = true;
				}
			}
		})
	},
	getTimeType: function(bool, type) {
		var arr = [{
			name: '固定时间',
			style: 'sect'
		}]
		return arr;
		if (bool) {
			var arr;
			if (type == 0) {
				arr = [{
					name: '固定时间',
					style: 'sect'
				}, {
					name: '自定义时间',
					style: 'unsect'
				}]
			} else {
				arr = [{
					name: '固定时间',
					style: 'unsect'
				}, {
					name: '自定义时间',
					style: 'sect'
				}]

			}

			return arr;
		} else {
			var arr = [{
				name: '固定时间',
				style: 'sect'
			}]
			return arr;
		}
	},
	fitArr: function(arr) { //过滤失效时间
		var oDate = new Date();
		//时  
		var oDateh = oDate.getHours();
		//分  
		var oDatemin = oDate.getMinutes();

		console.log('oDateh' + oDateh)
		console.log('oDatemin' + oDatemin)
		var showArr = [];
		for (var i = 0; i < arr.length; i++) {
			var hour = arr[i].split(':')[0];
			var min = arr[i].split(':')[1]
			if (oDateh < hour) {
				showArr.push(arr[i])
			} else if (oDateh == hour) {
				if (oDatemin < min) {
					showArr.push(arr[i])
				}
			}
		}
		console.log(showArr);
		return showArr;
	},
	bindGetUserInfo: function(e) {
		//console.log(e.detail.userInfo)
		this.updateMember(e.detail.userInfo.nickName, e.detail.userInfo.avatarUrl)
	},
	updateMember: function(name, img) {
		var _self = this;
		var paramInfo = {
			nickName: name,
			avatar: img

		}
		wx.request({
			url: getApp().globalData.baseUrl + '/wxappletMember/updateMember.do',
			method: "POST",
			data: paramInfo,
			header: getApp().globalData.header,
			success: function(res) {
				console.log(res)
				if (res.data.code == 200) {
					getApp().globalData.userInfo.nickName = name;
					getApp().globalData.userInfo.avatarUrl = img;
					_self.setData({
						isNeedwx: false
					})

				} else {

				}



			},
			fail: function() {
				console.log(1)
			}
		})

	},


})